package tips.javabeat.nio.lock;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileLockerTest {

    public static void main(String[] args) throws Exception {

        try{
        //TODO : choose if locked or unlocked. :D

        }catch (Exception exc){
        	System.out.println(""+exc.getMessage());
        }
    }
/*
    static void accessTheLockedFile(){

        try{
            FileInputStream input = new FileInputStream("FileToBeLocked");
            int data = input.read();
            System.out.println(data);
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }
*/
    static void unlockFile(File fileUnlock){
		try
        {
            RandomAccessFile file = new RandomAccessFile(fileUnlock, "rw");
            FileChannel fileChannel = file.getChannel();
			FileLock fileLock = null;

            if (fileLock != null){
                System.out.println("File is released");
                fileLock.release();
            }
        }catch (Exception ex){
        	System.out.println(""+ex.getMessage());
        }

    }


    static void lockFile(File fileTolock){
		try
        {
            RandomAccessFile file = new RandomAccessFile(fileTolock, "rw");
            FileChannel fileChannel = file.getChannel();
			FileLock fileLock = null;
            if (fileLock == null){
                fileLock = fileChannel.tryLock();
                System.out.println("File is locked");
            }
        }catch (Exception ex){
        	System.out.println(""+ex.getMessage());
        }

    }

}

